package com.zhanghu.backendZray.controller.permission;

import com.zhanghu.backendZray.annotation.MenuNeed;
import com.zhanghu.backendZray.manager.role.UserRoleMenuManager;
import com.zhanghu.backendZray.pojo.dto.ApiResponse;
import com.zhanghu.backendZray.pojo.request.OnlyIdRequest;
import com.zhanghu.backendZray.pojo.request.menu.MenuRequest;
import com.zhanghu.backendZray.pojo.vo.MenuVo;
import com.zhanghu.backendZray.service.MenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangdong
 * @since 2024-07-20
 */
@RestController
@RequestMapping("/menu")
@RequiredArgsConstructor
public class MenuController {
    private final MenuService menuService;
    private final UserRoleMenuManager userRoleMenuManager;

    @MenuNeed(menuName = "menu_manage")
    @PostMapping("add")
    public ApiResponse add(@Validated(MenuRequest.Create.class) @RequestBody MenuRequest menuRequest) {
        menuService.add(menuRequest);
        return ApiResponse.ok();
    }

    @MenuNeed(menuName = "menu_manage")
    @PutMapping("update")
    public ApiResponse update(@Validated(MenuRequest.Update.class) @RequestBody MenuRequest menuRequest) {
        menuService.update(menuRequest);
        return ApiResponse.ok();
    }

    @MenuNeed(menuName = "menu_manage")
    @PostMapping("delete")
    public ApiResponse delete(@RequestBody @NotNull OnlyIdRequest request) {
        Assert.notNull(request, "id不能为空");
        userRoleMenuManager.deleteMenu(request.getId().intValue());
        return ApiResponse.ok();
    }

    /**
     * 分页查询
     *
     * @param
     * @return
     */
//    @PostMapping("page")
//    public ApiResponse<Page<MenuVo>> page(@RequestBody MenuPageRequest menuPageRequest) {
//        Page<MenuVo> pageInfo = menuService.page(menuPageRequest);
//        return ApiResponse.ok(pageInfo);
//    }

    /**
     * tree格式输出
     */
    @MenuNeed(menuName = "menu_manage")
    @GetMapping("listAll")
    public ApiResponse<List<MenuVo>> listAll() {
        List<MenuVo> list = menuService.listAllTree();
        return ApiResponse.ok(list);
    }

}
